<?php


namespace App\Service;


use App\Exceptions\ApiException;
use DateTime;
use OSS\Core\OssException;
use OSS\OssClient;

class Qiuniuoss
{
    private  static $instance;
    public function __construct()
    {
        $this->endpoint = config('oss.aliyun.host');
        $this->accessKeyId = config('oss.aliyun.AccessKeyId');
        $this->accessKeySecret = config('oss.aliyun.AccessKeySecret');
        $this->bucket = config('oss.aliyun.bucket');
    }
    protected $endpoint = ''; //节点
    protected $accessKeyId = 'LTAI4FeNF9DdZksiF1UPDzsV'; //阿里云控制台子账号key
    protected $accessKeySecret = 'xDqI8YPVaTW7fqiUqtoLisPPrhX3hS'; //阿里云控制台子账号Secret
    protected $bucket = 'house-sell'; //oss控制台创建的bucket名称

    public static function instance(){
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    public  function gmt_iso8601($time) {
        $dtStr = date("c", $time);
        $mydatetime = new DateTime($dtStr);
        $expiration = $mydatetime->format(DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);
        return $expiration."Z";
    }

    public function makeAliyunOssSignData()
    {
        $id= $this->accessKeyId;          // 请填写您的AccessKeyId。
        $key= $this->accessKeySecret;     // 请填写您的AccessKeySecret。
        // $host的格式为 bucketname.endpoint，请替换为您的真实信息。
        $bucket = $this->bucket;
        $endpooint = $this->endpoint;
        $host = "http://{$bucket}.{$endpooint}";
        // $callbackUrl为上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实URL信息。
        $callbackUrl = url("/oss/callback");
        $dir = ''; //'user-dir-prefix/';          // 用户上传文件时指定的前缀。

        $callback_param = array('callbackUrl'=>$callbackUrl,
            'callbackBody'=>'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
            'callbackBodyType'=>"application/x-www-form-urlencoded");
        $callback_string = json_encode($callback_param);

        $base64_callback_body = base64_encode($callback_string);
        $now = time();
        $expire = 10*60;  //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问。
        $end = $now + $expire;
        $expiration = $this->gmt_iso8601($end);

        //最大文件大小.用户可以自己设置
        $condition = array(0=>'content-length-range', 1=>0, 2=>1048576000);
        $conditions[] = $condition;

        // 表示用户上传的数据，必须是以$dir开始，不然上传会失败，这一步不是必须项，只是为了安全起见，防止用户通过policy上传到别人的目录。
        $start = array(0=>'starts-with', 1=>'$key', 2=>$dir);
        $conditions[] = $start;


        $arr = array('expiration'=>$expiration,'conditions'=>$conditions);
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

        $response = array();
        $response['accessid'] = $id;
        $response['host'] = $host;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        $response['callback'] = $base64_callback_body;
        $response['dir'] = $dir;  // 这个参数是设置用户上传文件时指定的前缀。
       return $response;
    }

    public function getaliyunOssSignData($fileName)
    {
        $fileName = 'aa1101.png';
        $sign = self::signedUrl($fileName);
        $data = explode('?', $sign);
        $paramdata = explode('&', $data['1']);
        $res =  [];
        foreach ($paramdata as $k=>$v) {
            $arr = explode('=', $v);
            $res[$arr[0]] = $arr[1];
        }
        $res['host'] = $data[0];
       return $res;
    }


    public function signedUrl($filepath,array $options) { //filepath为bucket下不含bucket名称为图片路径
        $bucket = $this->getBucketName();
        $ossClient = $this->getOssClient();
        if (is_null($ossClient)) exit(1);
        $signedUrl = $ossClient->signUrl($bucket, $filepath, 3600,'GET',$options);
        return $signedUrl;
    }

   public function getOssClient()
    {
        try {
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint, false);
        } catch (OssException $e) {
            throw new ApiException($e->getMessage());
        }
        return $ossClient;
    }

    public function getBucketName()
    {
        return $this->bucket;
    }

}
